//
//  SLUserAccount.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/22.
//  Copyright © 2016年 大天朝. All rights reserved.
//
/*
    "access_token" = "2.00Y6ZEZFsYp2vB874724f88c8i3OIC";
    "expires_in" = 157679999;
    "remind_in" = 157679999;
    uid = 5098925356;
*/
import UIKit

//对象归档需要实现NSCoding

class SLUserAccount: NSObject, NSCoding {
    /*
    返回值字段	字段类型	字段说明
    access_token	string	用于调用access_token，接口获取授权后的access token。
    expires_in	string	access_token的生命周期，单位是秒数。
    remind_in	string	access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
    uid	string	当前授权用户的UID。
    */
    var access_token: String?
    
//    var expires_in: String?//实际新浪返回的不是String类型 是NSNumber类型
    //基本数据类型作为属性不能为可选.使用一个默认值
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }

    //过期时间
    var expiresDate: NSDate?
    
    var uid: String?
    
    //MARK: - 用户信息
    //用户名称
    var screen_name: String?
    //用户头像地址
    var avatar_large: String?
    
    /**
    *  使用KVC字典转模型
    */
    init(dict: [String: AnyObject]) {
        //没有在super.init()之前给属性赋值.属性需要定义为可选
        super.init()
        
        //使用KVC赋值
        setValuesForKeysWithDictionary(dict)
    }
    //字典中的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("forUndefinedKey: \(key)");
    }
    
    //对象的打印   description
    override var description: String {
        //只读计算性属性
        get {
            let keys = ["access_token", "expires_in", "expiresDate", "uid"]
            //拿着传入的key去模型中查找对应的属性
           return dictionaryWithValuesForKeys(keys).description
        }
    }
    
    //MARK: - 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init()//可以不调用
        //解档记得给属性赋值
       access_token = aDecoder.decodeObjectForKey("access_token") as? String
       expires_in = aDecoder.decodeDoubleForKey("expires_in")
       expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
       uid = aDecoder.decodeObjectForKey("uid") as? String
       avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
       screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
    
}


